# include "student.h"

Student * newStudent () {
	Student *new = (Student *) malloc(sizeof(Student));
	if (!new) logMessage("data","student","newStudent","Memória Insuficiente",CRITICAL);
	new->name = NULL;
	new->number = -1;
	new->type = -1;
	new->average = -1;
	new->selections = NULL;
	new->ucesWanted = 2;
	new->uceA = -1;
	new->uceB = -1;
	return new;
}

Selection * newSelection (char *uceName, int pref) {
	Selection *new = (Selection *) malloc(sizeof(Selection));
	if (!new) logMessage("data","student","newSelection","Memória Insuficiente",CRITICAL);
	new->uceName = uceName;
	new->preference = pref;
	return new;
}

void freeSelection (Selection *sel) {
	if (sel) {
		if (sel->uceName) free(sel->uceName);
		free(sel);
	}
}

void freeStudent (Student *st) {
	LinkedList *aux;
	Selection *sel;
	if (st) {
		if (st->name) free(st->name);
		aux = st->selections;
		while (aux) {
			sel = getData(aux);
			freeSelection(sel);
			aux = aux->next;
		}
		freeLinkedList(st->selections);
		free(st);
	}
}
int compareStudent (void *st1, void *st2) {
	Student *stA = st1;
	Student *stB = st2;
	if (stA->average > stB->average) return 1;
	else if (stA->average < stB->average) return -1;
	else {
		if (stA->year < stB->year) return 1;
		else if (stA->year > stB->year) return -1;
		else {
			return 1; // Grande sorte do 1º!
		}
	}
}
int equalStudent (void *sA, void *sB) {
	Student *stA = sA;
	Student *stB = sB;
	if (stA->number == stB->number) return 1;
	else return 0;
}

int compareSelection (void *s1, void *s2) {
	Selection *a = s1;
	Selection *b = s2;
	if (a->preference > b->preference) return 1;
	else if (a->preference < b->preference) return -1;
	else return 0;
}

int equalSelection (void *s1, void *s2) {
	Selection *a = s1;
	Selection *b = s2;
	return (!strcmp(a->uceName,b->uceName));
}

int isFirstSelection (Student *st, char *uce) {
	// lista de uces ordenada por preferência!
        if (!st) return 0;
        if (!uce) return 0;
	Selection *sel;
        LinkedList *aux = st->selections;
        int max = 0;
        int is = 0;
        while (aux) {
                sel = getData(aux);
                if (sel->preference > max) {
                        if (!strcmp(sel->uceName,uce)) is = 1;
                        else if (is) is = 0;
                        max = sel->preference;
                } else if (sel->preference == max) {
			if (!strcmp(sel->uceName,uce)) is = 1;
		}
                aux = aux->next;
        }
	return is;
}

char * getNextSelection (Student *st, char *actual) {
        if (!st) return NULL;
	int is = 0;
	if (!actual) is = 1;
        Selection *sel;
        LinkedList *aux = st->selections;
        if (actual < 0) is = 1;
        while (aux) {
                sel = getData(aux);
                if (is) return sel->uceName;
                if (!strcmp(sel->uceName,actual)) is = 1;
                aux = aux->next;
        }
        return NULL;

}
